package com.strawcom.charmring.view;

import java.util.ArrayList;
import java.util.List;

import org.kymjs.kjframe.KJBitmap;
import org.kymjs.kjframe.utils.DensityUtils;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;

import com.strawcom.charmring.R;
import com.strawcom.charmring.bean.Alert;
import com.strawcom.charmring.util.HttpUtil;

/**
 * 
 * @ClassName: HeadHorizontalScrollView
 * @Description:地图顶部头像容器自定义控件
 * @author liyongqiang
 * @date 2015-4-1 下午11:46:50
 * 
 */
public class HeadHorizontalScrollView extends HorizontalScrollView {

	private LinearLayout headsContainer;
	private LinearLayout.LayoutParams defaultHeadsLayoutParams;
	private int itemWidth;
	private int[] location = new int[2];
	private float downX;
	private float moveX;
	private float upX;
	private float scrollX;
	private boolean isScroll = false;
	private int marginDp;
	private List<LightDarkRoundImageView> imgHeadVies = null;
	private LayoutInflater inflater;
	private List<View> delateViews;
	private View layoutRight;
	private List<Alert> list;
	private MapFrameLayout mapFrameLayout;

	public HeadHorizontalScrollView(Context context) {
		this(context, null);
	}

	public HeadHorizontalScrollView(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public HeadHorizontalScrollView(Context context, AttributeSet attrs,
			int defStyle) {
		super(context, attrs, defStyle);

		setFillViewport(true);
		setWillNotDraw(false);

		inflater=LayoutInflater.from(getContext());
		headsContainer = new LinearLayout(context);
		headsContainer.setOrientation(LinearLayout.HORIZONTAL);
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		headsContainer.setLayoutParams(lp);
		addView(headsContainer);

		marginDp = DensityUtils.dip2px(context, 10);
		itemWidth = DensityUtils.dip2px(context, 40);
		defaultHeadsLayoutParams = new LinearLayout.LayoutParams(itemWidth,
				LayoutParams.MATCH_PARENT);
		defaultHeadsLayoutParams.setMargins(marginDp, marginDp, marginDp,
				marginDp);
	}

	private void addHead(int position, Alert alert, boolean isMyself) {
		View view=inflater.inflate(R.layout.layout_head_img, null);
		LightDarkRoundImageView imgHead=(LightDarkRoundImageView) view.findViewById(R.id.img_head);
		View layoutDelete=view.findViewById(R.id.layout_delete);
		layoutDelete.setTag(position);
		layoutDelete.setOnClickListener(deleteClick);
		if(delateViews==null){
			delateViews=new ArrayList<View>();
		}
		delateViews.add(layoutDelete);
		KJBitmap kjb = KJBitmap.create();
		kjb.display(imgHead, HttpUtil.url_img +  alert.getIcon());
		
		imgHead.setId(position - offset); // 位置标志
		imgHead.setOnClickListener(imgHeadClick);
		if (isMyself) {
			imgHead.setLightDark(LightDarkRoundImageView.light);
			imgHead.setTag(LightDarkRoundImageView.tag);
		}
		if (imgHeadVies == null) {
			imgHeadVies = new ArrayList<LightDarkRoundImageView>();
		}
		imgHeadVies.add(imgHead);
		headsContainer.addView(view, position, defaultHeadsLayoutParams);
	}

	View.OnClickListener imgHeadClick = new OnClickListener() {

		@Override
		public void onClick(View view) {
			setLightView(view);
			
			if(listener != null) {
				int position = view.getId();
				listener.onSelectedChanged(position);
			}
		}
	};
	
	public interface OnSelectedChangedListener {
		void onSelectedChanged(int position ) ;
	}
	
	public OnSelectedChangedListener listener ;
	
	public void setOnHeadClickListener(OnSelectedChangedListener listener) {
		this.listener = listener;
	}
	
	View.OnClickListener deleteClick=new OnClickListener() {
		
		@Override
		public void onClick(View view) {
			int poistion=Integer.parseInt(view.getTag().toString());
			int showCount=0;
			headsContainer.getChildAt(poistion).setVisibility(View.GONE);
			int count=headsContainer.getChildCount();
			for (int i = 0; i < count; i++) {
				View v=headsContainer.getChildAt(i);
				if(v.isShown()){
					showCount++;
				}
			}
			if(showCount==2){
				layoutRight.setVisibility(View.GONE);
				mapFrameLayout.setTouchFlag(true);
			}
			//imgHeadVies.remove(poistion-1);
			//delateViews.remove(poistion-1);
			
			// delete data on database!
//			int poistion=Integer.parseInt(view.getTag().toString());
//			Toast.makeText(getContext(), "del:positon" + poistion, Toast.LENGTH_SHORT).show();
//				}			}
			
//				}			
//			}
			list.get(poistion-1).delete();
			if(showCount==2){
				layoutRight.setVisibility(View.GONE);
				mapFrameLayout.setTouchFlag(true);
				mapFrameLayout.setVisibility(View.GONE);
			}else{
				List<LightDarkRoundImageView> shownViews=new ArrayList<LightDarkRoundImageView>();
				for (LightDarkRoundImageView imageView : imgHeadVies) {
					if(imageView.isShown()){
						shownViews.add(imageView);
					}
				}
				if(shownViews.size()>0){
					int curr=shownViews.size()/2;
					setLightView(shownViews.get(curr));
					int position = shownViews.get(curr).getId();
					if(listener != null) {
						listener.onSelectedChanged(position);
					}
				}
			}
		}
	};
	
	View.OnClickListener btnClick=new OnClickListener() {
		
		@Override
		public void onClick(View view) {
			Button btn=(Button)view;
			if(btn.getText().equals(getResources().getString(R.string.edit))){
				for (View delView : delateViews) {
					delView.setVisibility(View.VISIBLE);
					mapFrameLayout.setTouchFlag(false);
				}
				btn.setText(R.string.cancel);
				
			}else{
				for (View delView : delateViews) {
					delView.setVisibility(View.GONE);
					mapFrameLayout.setTouchFlag(true);
				}
				btn.setText(R.string.edit);
			}
		}
	};;

	private void setLightView(final View view) {
		for (LightDarkRoundImageView imageView : imgHeadVies) {
			imageView.setLightDark(LightDarkRoundImageView.dark);
			imageView.setTag("");
		}
		((LightDarkRoundImageView) view)
				.setLightDark(LightDarkRoundImageView.light);
		((LightDarkRoundImageView) view).setTag(LightDarkRoundImageView.tag);

		view.getLocationInWindow(location);
		smoothScrollBy(
				location[0]
						- (DensityUtils.getScreenW(getContext()) - view.getWidth())
						/ 2, 0);
	}

	private void addEmptyView(int position) {
		View empty = new LinearLayout(getContext());
		LinearLayout.LayoutParams emptyLayoutParams = new LinearLayout.LayoutParams(
				DensityUtils.getDialogW(getContext()) / 2,
				LayoutParams.MATCH_PARENT);
		headsContainer.addView(empty, position, emptyLayoutParams);
	}
	
	private void addRightView(int poistion){
		LinearLayout.LayoutParams rightLayoutParams = new LinearLayout.LayoutParams(
				DensityUtils.getDialogW(getContext()) / 2,
				LayoutParams.MATCH_PARENT);
		layoutRight=inflater.inflate(R.layout.layout_head_right, null);
		Button btnEdit=(Button) layoutRight.findViewById(R.id.btn_edit);
		btnEdit.setOnClickListener(btnClick);
		headsContainer.addView(layoutRight, poistion, rightLayoutParams);
	}
	
	private int offset = 1; // 偏移

	public void setHeadList(List<Alert> alertInfoList, final int myselfPoistion,MapFrameLayout layoutMapFrame) {
		headsContainer.removeAllViews();
		imgHeadVies=null;
		delateViews=null;
		this.list=alertInfoList;
		this.mapFrameLayout=layoutMapFrame;
		addEmptyView(0);
		for (int i = 0; i < list.size(); i++) {
			addHead(i + offset, list.get(i), i == myselfPoistion);
		}
		addRightView(list.size() + offset);
		post(new Runnable() {
			
			@Override
			public void run() {
				int scrollX=(itemWidth+2*marginDp)*myselfPoistion+marginDp;
				if(getScrollX()!=0){
					scrollTo(0, 0);
				}
				smoothScrollBy(scrollX, 0);
			}
		});
	}
	
	public void setSelection(int position) {
		setLightView(imgHeadVies.get(position));
		/*position = position + offset;
		int scrollX=(itemWidth+2*marginDp)*position+marginDp;
		if(getScrollX()!=0){
			scrollTo(0, 0);
		}
		smoothScrollBy(scrollX, 0);*/
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		isScroll = false;
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			downX = event.getX();
			break;
		case MotionEvent.ACTION_MOVE:
			moveX = event.getX();
			scrollX = moveX - downX;
			if (Math.abs(scrollX) > 5) {// 认为水平滑动，由HorizontalScrollView处理事件
				isScroll = true;
				super.onTouchEvent(event);
			}
			break;
		case MotionEvent.ACTION_UP:
			upX = event.getX();
			scrollX = upX - downX;
			if (Math.abs(scrollX) > 5) {
				isScroll = true;
				super.onTouchEvent(event);
			}
			if (isScroll) {
				View view = findViewWithTag(LightDarkRoundImageView.tag);
				if (view != null && view instanceof LightDarkRoundImageView) {
					view.getLocationInWindow(location);
					smoothScrollBy(
							location[0]
									- (DensityUtils.getScreenW(getContext()) - view.getWidth())
									/ 2, 0);
					
					if(listener != null) {
						int position = view.getId();
						listener.onSelectedChanged(position);
					}
				}
				return true;
			}
			break;
		default:
			break;
		}
		return false;
	}

	@Override
	protected void onScrollChanged(int l, int t, int oldl, int oldt) {
		super.onScrollChanged(l, t, oldl, oldt);
		for (LightDarkRoundImageView imageView : imgHeadVies) {
			imageView.isInCenter(imgHeadVies);
		}
	}
	
}
